package com.subtlman.logframework.queue;

/**
 * @Create: IntelliJ IDEA.
 * @Author: subtlman_ljx
 * @Date: 2022/11/18/18:04
 * @Description:
 */
class InterruptFlag {
    // 自定义的中断标识符
    private static volatile boolean isInterrupt = false;

    public static void main(String[] args) throws InterruptedException {
        // 创建可中断的线程实例
        Thread thread = new Thread(() -> {
            while (!isInterrupt) { // 如果 isInterrupt=true 则停止线程
                System.out.println("thread 执行步骤1：线程即将进入休眠状态");
                try {
                    // 休眠 1s
                    Thread.sleep(5000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                System.out.println("thread 执行步骤2：线程执行了任务");
            }

            Thread thread2 = new Thread(() -> {
                while (!isInterrupt) { // 如果 isInterrupt=true 则停止线程
                    System.out.println("thread 执行步骤1：线程即将进入休眠状态");
                    try {
                        // 休眠 1s
                        Thread.sleep(5000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    System.out.println("thread 执行步骤2：线程执行了任务");
                }

            });
            thread2.start();
        });
        thread.start(); // 启动线程

        // 休眠 100ms，等待 thread 线程运行起来
        Thread.sleep(100);
        System.out.println("主线程：试图终止线程 thread");
        // 修改中断标识符，中断线程
        isInterrupt = true;
    }
}

